package com.litchi.pools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;

/**
 * @Author: Jiangxx
 * @Date: 2023/09/08
 * @Description:
 */
public class ShutdownHookThread extends Thread {

    private volatile boolean hasShutdown = false;

    private final Callable callback;

    private static final Logger logger = LoggerFactory.getLogger(ShutdownHookThread.class);


    public ShutdownHookThread(String name, Callable callback) {
        super("JVM退出钩子(" + name + ")");

        this.callback = callback;
    }

    @Override
    public void run() {
        synchronized (this) {
            if (!this.hasShutdown) {
                this.hasShutdown = true;
                long beginTime = System.currentTimeMillis();
                try {
                    this.callback.call();
                } catch (Exception e) {
                    logger.info(e.getMessage());
                }
                long consumingTimeTotal = System.currentTimeMillis() - beginTime;
                logger.info("耗时：" + consumingTimeTotal + "毫秒");
            }
        }
    }

}
